package com.kingcore.director.setting.ui;

import java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;

import wzw.beans.DbBean;
import wzw.swing.table.PlainTable;
import wzw.swing.table.PlainTableModel;
import wzw.util.ComponentUtil;

import com.kingcore.director.DirectorConstants;
import com.kingcore.director.base.ui.DirectorDialog;
import com.kingcore.director.core.ui.ProcessingDialog;
import com.kingcore.director.main.MainFrame;
import com.kingcore.director.setting.bean.FilesBackupBean;
import com.sunking.swing.JFileTree;
import com.sunking.swing.JFileTree.AllFileFilter;
import com.sunking.swing.JTreeComboBox;

public class FileBackupDialog extends DirectorDialog 
		implements ActionListener,ItemListener, MouseListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected static final int MainTable_Column_Index_Location = 0;
	private JPanel mainPanel = null;
	private JLabel jLabel = null;
	private JComboBox lbbh = null;
	private JLabel jLabel1 = null;
	private JComboBox path = null;	//JTextField
	private JButton btnAdd = null;
	private JButton btnDel = null;
	private JScrollPane jScrollPane = null;
	private PlainTable table = null;
	private MainFrame mf;
	
	/**
	 * This method initializes lbbh	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getLbbh() {
		if (lbbh == null) {
			lbbh = new JComboBox();
			lbbh.setBounds(new java.awt.Rectangle(121,10,245,23));
			lbbh.addItemListener( this );
		}
		return lbbh;
	}

//	/**
//	 * This method initializes path	
//	 * 	
//	 * @return javax.swing.JTextField	
//	 */
//	private JTextField getPath() {
//		if (path == null) {
//			path = new JTextField();
//			path.setBounds(new java.awt.Rectangle(121,47,175,27));
//			path.setEnabled( false );
//		}
//		return path;
//	}

	/**
	 * This method initializes path	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getPath() {
		if (path == null) {
			path = new JTreeComboBox();	//JComboBox();
			path.setBounds(new java.awt.Rectangle(121,39,245,23));
			((JTreeComboBox)path).setTree(new JFileTree( new AllFileFilter() ));
		}
		return path;
	}

	/**
	 * This method initializes btnAdd	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnAdd() {
		if (btnAdd == null) {
			btnAdd = new JButton();
			btnAdd.setBounds(new java.awt.Rectangle(234,71,80,25));
			btnAdd.setText("添加(A)");
			btnAdd.addActionListener( this );
		}
		return btnAdd;
	}

	/**
	 * This method initializes btnDel	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnDel() {
		if (btnDel == null) {
			btnDel = new JButton();
			btnDel.setBounds(new java.awt.Rectangle(323,71,77,25));
			btnDel.setText("删除(D)");
			btnDel.addActionListener( this );
		}
		return btnDel;
	}

	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setBounds(new java.awt.Rectangle(5,95,418,195));
			jScrollPane.setViewportView(getTable());
		}
		return jScrollPane;
	}

	/**
	 * This method initializes table	
	 * 	
	 * @return javax.swing.JTable	
	 */
	private PlainTable getTable() {
		if (table == null) {
			table = new PlainTable();
		    DefaultTableModel dtm = new DefaultTableModel(1,1); //no new methods
		    PlainTableModel sorter = new PlainTableModel( dtm, table.getTableHeader());
		    table.setModel(sorter);
			table.setEnabled(true);
			table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
			
			table.setShowGrid(true);
			table.setSelectionMode(javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
			//tztj.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			table.getTableHeader().setReorderingAllowed(false);
			//table.setForeground(Color.blue);
			table.getModel().getTableModel().setColumnIdentifiers( new String[]{"文件路径"});
			table.showZebraCross();

			table.addMouseListener(this);	
		}
		return table;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	/**
	 * This is the default constructor
	 */
	public FileBackupDialog() {
		this(null);
	}

	public FileBackupDialog(MainFrame frame) {
		super(frame, true);
		this.mf = frame ;
		initialize();
		try {
			fetchData();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private boolean fetchData() throws SQLException {
		//step
		ComponentUtil.initComboBox( getLbbh(),"Select Val,Txt,isDefault,Orderby From "+DirectorConstants.SYS_Class+" Where LBBH='000002' Order By orderby asc" );

//		//step
//		String sql =  "SELECT VAL FROM "+DirectorConstants.SYS_Setting +
//				          " Where KEY='"+DirectorConstants.File_Backup_CurrentSort+"'" ;
//		DbBean dbBean = new DbBean();
//		String defaultType = dbBean.queryForString(sql);
//		ComponentUtil.setSelectedItemByCode( getLbbh(), defaultType);

		//step
		String ts_lbbh = ComponentUtil.getSelectedItemCode( getLbbh() );
		ComponentUtil.initTable( getTable(),"Select Path From "+DirectorConstants.FMT_FileBackup+" Where LBBH='"+ts_lbbh+"' Order by Path asc" );
		return true;		
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(434, 327);
		this.setResizable(false);
		this.setTitle("文件备份设置");
		this.setContentPane(getMainPanel());
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getMainPanel() {
		if (mainPanel == null) {
			jLabel1 = new JLabel();
			jLabel1.setBounds(new java.awt.Rectangle(14,39,113,23));
			jLabel1.setText("要备份的文件(夹)：");
			jLabel = new JLabel();
			jLabel.setBounds(new java.awt.Rectangle(14,10,115,23));
			jLabel.setText("       文件备份类别：");  //内容中的空格是为了与其他Label内容右对其
			mainPanel = new JPanel();
			mainPanel.setLayout(null);
			mainPanel.add(jLabel, null);
			mainPanel.add(getLbbh(), null);
			mainPanel.add(jLabel1, null);
			mainPanel.add(getPath(), null);
			mainPanel.add(getBtnAdd(), null);
			mainPanel.add(getBtnDel(), null);
			mainPanel.add(getJScrollPane(), null);
		}
		return mainPanel;
	}
	
	/**
	 * implements ActionListener
	 */
	public void actionPerformed(ActionEvent e) {
		Object src = e.getSource();
		// 添加
		if(src==btnAdd){
			String ts_lbbh = ComponentUtil.getSelectedItemCode( getLbbh() );
			String ts_path ;

			if( ts_lbbh==null || ts_lbbh.trim().equals("")){
				JOptionPane.showMessageDialog(this,"没有类别编号！");
				lbbh.requestFocus();
				return;
			}

			if( getPath().getSelectedItem()==null ){
				JOptionPane.showMessageDialog(this,"请选择路径！");
				path.requestFocus();
				return;
			} else {
				//ts_path = getPath().getSelectedItem().toString();
				ts_path = ((JFileTree)((JTreeComboBox)getPath()).getTree()).getSelectFile().getPath() ;
				// ts_path = ts_path.replace("\\","/"); //by wzw:keep as same as File.separator
//				if( !ts_path.endsWith( File.separator )){
//					ts_path += File.separator.;
//				}
			}
			
			String sql="Insert Into "+DirectorConstants.FMT_FileBackup+"(LBBH,PATH) " +
					"Values('"+ts_lbbh+"','"+ 
							   ts_path+"')";
			DbBean dbBean = new DbBean(DbBean.DefaultPoolName);
			try {
				dbBean.executeUpdate( sql );
				Vector v_row = new Vector();
				v_row.add(ts_path);
				DefaultTableModel dtm = this.getTable().getModel().getTableModel();
				dtm.addRow(v_row);
			} catch (SQLException e1) {
				JOptionPane.showMessageDialog(this,e1.getMessage(),"数据库操作失败",JOptionPane.ERROR_MESSAGE);
				e1.printStackTrace();
				return;
			}
			

		// 删除
		} else if( src==btnDel ){
			int row = getTable().getSelectedRow();
			if(row<0){
				JOptionPane.showMessageDialog(this,"请选择要删除的行！");
				return ;
			}
			
			if(JOptionPane.showConfirmDialog(this,"确认删除当前信息吗？","提示",JOptionPane.OK_CANCEL_OPTION)
					!=JOptionPane.OK_OPTION)
				return;
			String ts_lbbh = ComponentUtil.getSelectedItemCode( getLbbh() );
			String ts_path  = getTable().getValueAt( row,0).toString();

			String sql="Delete From "+DirectorConstants.FMT_FileBackup +
					" Where LBBH='"+ts_lbbh+"' "+ 
					  " And PATH ='"+ts_path+"'";
			DbBean dbBean = new DbBean(DbBean.DefaultPoolName);
			try {
				dbBean.executeUpdate( sql );
				table.getModel().getTableModel().removeRow( row );
			} catch (SQLException e1) {
				JOptionPane.showMessageDialog(this,e1.getMessage(),"数据库操作失败",JOptionPane.ERROR_MESSAGE);
				e1.printStackTrace();
				return;
			}

		} else if( src==jpmi_MainTable_doBackup ){

			//step: check input 
			final int[] selRows = getTable().getSelectedRows(); // support multi rows
			if (selRows==null || selRows.length<1) {
				JOptionPane.showMessageDialog(this, "请先选择要备份的行！", "提示", JOptionPane.INFORMATION_MESSAGE);
				return;
			}
			
			if(JOptionPane.showConfirmDialog(this,"确认马上执行选中的行备份吗？", "提示",JOptionPane.OK_CANCEL_OPTION) //"确认复制所有文件，并且确认当前系统时间准确吗？"
					!=JOptionPane.OK_OPTION)
				return;
			final Dialog parent = this;

			//实现正在处理...效果
			Thread thread = new Thread(){
				public void run(){
					try {
						
						String fileUri = null;
						DefaultTableModel dtm = table.getModel().getTableModel();
						List<String> fileUriList = new ArrayList<String>();
						for (int i=selRows.length-1; i>-1; i--) {
							fileUri = dtm.getValueAt( selRows[i], MainTable_Column_Index_Location).toString();
							fileUriList.add(fileUri);				
						}
						
						//String[] args = new String[]{"-destPath"+destPath, "-backupSort"+backupSort};
						//FilesBackupBean.main(args);
						FilesBackupBean.executeBackup(fileUriList);
						JOptionPane.showMessageDialog(parent, "执行备份成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
					} catch (Exception e) {
						e.printStackTrace();
						JOptionPane.showMessageDialog(null,e.getMessage(),"执行备份失败",JOptionPane.ERROR_MESSAGE);
					}
				}
			};
			
			ProcessingDialog.showInstance(parent, thread ,
						"正在执行，请等待......");//启动等待提示框线程,能否把现实做为线程，对其他代码改动下？
			
		}
		
	}


	private JPopupMenu popupMenuForTable;
	private JMenuItem jpmi_MainTable_doBackup;
	/**
	 * Table的弹出式菜单
	 */
	private JPopupMenu getPopupMenuForTable(){
		
		if(popupMenuForTable == null){
			popupMenuForTable = new JPopupMenu();
			
			jpmi_MainTable_doBackup = new JMenuItem();
			jpmi_MainTable_doBackup.setText("马上备份选中的行");
			jpmi_MainTable_doBackup.addActionListener( this );
			 
			popupMenuForTable.add( jpmi_MainTable_doBackup ) ;
			
		}
		return popupMenuForTable;
	}
		
	/**
	 * implements ItemListener
	 * @param e
	 */
	public void itemStateChanged(ItemEvent e) {
		Object src = e.getSource();
		if(src==lbbh){
			String ts_lbbh = ComponentUtil.getSelectedItemCode( getLbbh() );
			ComponentUtil.initTable( getTable(),"Select Path From "+DirectorConstants.FMT_FileBackup+" Where LBBH='"+ts_lbbh+"' Order by Path asc" );
		}
		
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		Object obj = e.getSource() ;
		if(obj==getTable()){
			// 在Table上右击鼠标
			//System.out.println ( " getPopupMenuForTable 1");
			if( e.getButton() == MouseEvent.BUTTON3 ) {	//显示弹出菜单
				//Object t_name = mainTable.getValueAt(mainTable.getSelectedRow(), MainTable_Column_Index_Name);
				//getPopupMenuForTable().setSelected(null);
				getPopupMenuForTable().show( e.getComponent(), e.getX(), e.getY() );
				
			}
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

}  //  @jve:decl-index=0:visual-constraint="10,10"
